<template>
  <div class="history-data-wrap flex h-full flex-col overflow-hidden p-4">
    <div class="chart-box flex-end flex w-full">
      <slot
        name="innerHeader"
        class="flex w-1/2 justify-start"
        v-if="hasInnerHeader"
      ></slot>
      <Compact
        class="flex justify-end"
        :style="{ width: hasInnerHeader ? '50%' : '100%' }"
      >
        <template v-if="!opt.hideDatePicker">
          <RangePicker
            v-model:value="date"
            show-time
            :format="timeFormat"
            :value-format="timeFormat"
            :disabled-date="disabledDate"
          ></RangePicker>
        </template>
        <Button @click="onDownload" :disabled="hasData">下载</Button>
      </Compact>
    </div>
    <Spin :spinning="loading">
      <div class="relative h-full w-full overflow-hidden bg-[#103B62]">
        <div
          v-if="hasData"
          class="absolute left-0 top-0 flex h-full w-full items-center justify-center"
        >
          暂无数据
        </div>

        <div :id="id" class="relative z-10 h-full w-full"></div>
      </div>
    </Spin>
  </div>
</template>

<script setup lang="tsx">
import { computed, inject, onMounted, ref, useId, watch } from 'vue';
import { Button, Compact, RangePicker, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useRequest } from 'vue-request';
import { realDataChart } from '@/utils/index';
import { downloadHistoryData, fetchHistoryData } from './api';

const opt = inject(
  'historyDataOption',
  computed(() => ({
    startTime: '',
    endTime: '',
    hideDatePicker: false,
  })),
);

const slots = defineSlots();
const hasInnerHeader = computed(() => {
  return slots.hasOwnProperty('innerHeader');
});

const id = useId();
const timeFormat = 'YYYY-MM-DD HH:mm:ss';

const date = ref<[string, string]>([
  dayjs().add(-10, 'm').format(timeFormat),
  dayjs().format(timeFormat),
]);
const disabledDate = (date) => {
  return dayjs().isBefore(date);
};

const props = defineProps({
  channel: {
    type: Array,
    default: () => [],
  },
  presentation: {
    type: Array,
    default: () => [],
  },
  instanceOptions: {
    type: Object,
    default: () => {},
  },
  deviceInfo: {
    type: Array,
    default: () => [],
  },
});
const code = computed(() => props.deviceInfo[0]);

const channels = computed(() => {
  return props.instanceOptions.channelList
    .filter((item) => props.channel.includes(item.value))
    .map((cur, index) => {
      const { value, color } = cur;
      return {
        color,
        name: value,
        yName: '单位: 度(°)',
        grid: {
          show: true,
          top: `${30 * index + 5} + %`,
          left: '3%',
          right: '3%',
          height: `${100 / 3 - 10}%`,
          containLabel: true,
        },
      };
    });
});

const params = computed(() => {
  const [startTime, endTime] = date.value;

  return {
    startTime: opt.value.startTime || startTime,
    endTime: opt.value.endTime || endTime,
    stationId: code.value,
  };
});

const { loading, runAsync } = useRequest(fetchHistoryData, { manual: true });

const hasData = ref(true);
const refreshData = async () => {
  const { renderChart } = realDataChart({
    target: document.getElementById(id),
    // title: `设备标识：${code} | 采样率：${samplingRate} | 烈度：${intensity}`,
    title: false,
    direction: 'vertical',
    channels: channels.value,
    once: true,
  });
  const res = await runAsync(params.value);
  hasData.value = Object.keys(res.data).length <= 0;
  if (hasData.value) return;
  const dataSource = {};
  Object.keys(res.data).map((_key) => {
    let key;
    switch (_key) {
      case 'Z':
        key = 'EIZ';
        break;
      case 'N':
        key = 'EIN';
        break;
      case 'E':
        key = 'EIE';
        break;
      default:
        break;
    }
    dataSource[key] = res.data[_key].reduce((prev, cur) => {
      if (cur[0] % 100 === 0) {
        prev.push(cur);
      }
      return prev;
    }, []);
  });

  renderChart(dataSource);
};

onMounted(() => {
  refreshData();
});

watch(
  () => channels.value,
  () => {
    refreshData();
  },
);

watch(
  () => date.value,
  () => refreshData(),
  {
    deep: true,
  },
);

const onDownload = async () => {
  downloadHistoryData(params.value);
};
</script>

<style lang="scss" scoped>
:deep(.ant-spin-nested-loading) {
  width: 100%;
  flex: 1;

  .ant-spin-container {
    width: 100%;
    height: 100%;
  }
}
</style>
